package com.cooba.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/10/14.
 */
public class BitmapZipUtil {

    private static String filename;

    public static File scal(String path,Context context){
        //String path = fileUri.getPath();
        filename=path.substring(path.lastIndexOf("/")+1);
        File outputFile = new File(path);
        long fileSize = outputFile.length();
        final long fileMaxSize = 400 * 1024;
        Log.d("wei","length_old:"+fileSize);
        int scale=1;
        if (fileSize>= fileMaxSize) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;

            //double scale = Math.sqrt((float) fileSize / fileMaxSize);
            scale=(int) (scale + 0.5);
            options.outHeight = (int) (height / scale);
            options.outWidth = (int) (width / scale);
            options.inSampleSize =scale;
            options.inJustDecodeBounds = false;

            // 缩放图片的尺寸
            float w = options.outWidth;
            float h = options.outHeight;

            int ww = context.getResources().getDisplayMetrics().widthPixels;
            int hh = context.getResources().getDisplayMetrics().heightPixels;
            // 最长宽度或高度1024
            int be = 1;
            if (w > h && w > ww) {
                be = (int) (w / ww);
            } else if (w < h && h > hh) {
                be = (int) (h / hh);
            }
            if (be <= 0) {
                be = 1;
            }
            options.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            int desWidth = (int) (w / be);
            int desHeight = (int) (h / be);
            bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);

            outputFile = new File(createImageFile().getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("wei","length_new:" + outputFile.length());
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }else{
                File tempFile = outputFile;
                outputFile = new File(createImageFile().getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }

        }
        return outputFile;

    }
    public static Uri createImageFile(){
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_"+filename;
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = null;
        if (!storageDir.exists()){
            storageDir.mkdirs();
        }
        image=new File(storageDir,imageFileName);
//        try {
//            if (!storageDir.exists()){
//                storageDir.mkdirs();
//            }
//            image=new File(storageDir,imageFileName);
//            //image=File.createTempFile(imageFileName,".jpg",storageDir);
////            image = File.createTempFile(imageFileName, /* prefix */
////                    .jpg,         /* suffix */
////                    storageDir      /* directory */
////            );
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

        // Save a file: path for use with ACTION_VIEW intents
        return Uri.fromFile(image);
    }
    public static void copyFileUsingFileChannels(File source, File dest){
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            try {
                inputChannel = new FileInputStream(source).getChannel();
                outputChannel = new FileOutputStream(dest).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } finally {
            try {
                inputChannel.close();
                outputChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void compressPicture(String srcPath, String desPath) {
        FileOutputStream fos = null;
        BitmapFactory.Options op = new BitmapFactory.Options();

        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        op.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
        op.inJustDecodeBounds = false;

        // 缩放图片的尺寸
        float w = op.outWidth;
        float h = op.outHeight;
        float hh = 1024f;//
        float ww = 1024f;//
        // 最长宽度或高度1024
        float be = 1.0f;
        if (w > h && w > ww) {
            be = (float) (w / ww);
        } else if (w < h && h > hh) {
            be = (float) (h / hh);
        }
        if (be <= 0) {
            be = 1.0f;
        }
        op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, op);
        int desWidth = (int) (w / be);
        int desHeight = (int) (h / be);
        bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
        try {
            fos = new FileOutputStream(desPath);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}
